package com.nuanfeng.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nuanfeng.wiki.domain.Ebook;
import com.nuanfeng.wiki.domain.EbookExample;
import com.nuanfeng.wiki.mapper.EbookMapper;
import com.nuanfeng.wiki.req.EbookQueryReq;
import com.nuanfeng.wiki.req.EbookSaveReq;
import com.nuanfeng.wiki.resp.EbookQueryResp;
import com.nuanfeng.wiki.resp.PageResp;
import com.nuanfeng.wiki.util.CopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EbookService {

    private static final Logger LOG =  LoggerFactory.getLogger(EbookService.class);

    @Resource
    EbookMapper ebookMapper;

    public PageResp<EbookQueryResp> list(EbookQueryReq req){

        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria(); //criteria：相当于where条件
        if(!ObjectUtils.isEmpty(req.getName())){    //如果name不为空就执行 like查询
            criteria.andNameLike("%"+req.getName()+"%");
        }

        PageHelper.startPage(req.getPage(),req.getSize());
        //持久层返回List<Ebook> 需要转成List<Ebook Resp> 再返回controller
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);

        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);
        LOG.info("总行数：{}",pageInfo.getTotal());
        LOG.info("总页数：{}",pageInfo.getPages());

//        List<EbookResp> respList=new ArrayList<>();
//        for (Ebook ebook : ebookList) {
//            EbookResp ebookResp = new EbookResp();
//            BeanUtils.copyProperties(ebook,ebookResp);//工具类：将ebook数据拷贝给ebookResp
//            respList.add(ebookResp);
//        }
        List<EbookQueryResp> respList= CopyUtil.copyList(ebookList, EbookQueryResp.class);
        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(respList);
        return pageResp;
    }

    //保存
    public void save(EbookSaveReq req){
        Ebook ebook=CopyUtil.copy(req, Ebook.class);
        if(ObjectUtils.isEmpty(req.getId())){
            // 新增
            ebookMapper.insert(ebook);
        }else{
            //更新
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

}
